package de.herberlin.pss.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.TableModel;

import org.apache.log4j.Logger;

import de.herberlin.pss.ServiceLocator;
import de.herberlin.pss.action.DefaultDataAction;
import de.herberlin.pss.action.DeleteAction;
import de.herberlin.pss.action.ImportAction;

public class Frame extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private static Frame _instance = null;

	public Frame() {
		_instance = this;
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("PSS-Client");

		this.setJMenuBar(new AppMenu().getAppMenu(this));
		this.setLayout(new BorderLayout());
		this.add(getNorth(), BorderLayout.NORTH);
		this.add(getCenter(), BorderLayout.CENTER);
		this.setSize(new Dimension(320, 240));
		this.setVisible(true);
		showCoosePssFileDialog();

	}

	private static JProgressBar progressBar=null;
	
	private JToolBar getNorth() {
		JToolBar bar = new JToolBar();

		// add button
		JButton button = new JButton(ServiceLocator.getText("Frame.add"),ServiceLocator.getImage("Add"));
		button.setActionCommand("add");
		button.addActionListener(this);
		bar.add(button);

		// delete button
		button = new JButton(ServiceLocator.getText("Frame.delete"),ServiceLocator.getImage("Remove"));
		button.setActionCommand("delete");
		button.addActionListener(this);
		bar.add(button);

		// Progress Bar
		progressBar = new JProgressBar();
		progressBar.setIndeterminate(true);
		progressBar.setString("Working..");
		progressBar.setStringPainted(true);
		progressBar.setVisible(false);
		progressBar.setBorderPainted(false);
		bar.add(progressBar);

		return bar;
	}

	private static Logger logger = Logger.getLogger(Frame.class);

	private JTable table = null;

	private JPanel getCenter() {
		JPanel p = new JPanel(new BorderLayout());
		table = new JTable();
		TableModel model = SongTableModel.getInstance();
		model.addTableModelListener(table);
		table.setModel(model);
		// table.setDropMode(DropMode.INSERT_ROWS);
		// table.setRowSorter(new TableRowSorter(model));
		ImportTransferHandler handler = new ImportTransferHandler();
		table.setTransferHandler(handler);
		JScrollPane scroll = new JScrollPane(table);
		scroll.setTransferHandler(handler);
		p.add(scroll);
		return p;
	}

	public void actionPerformed(ActionEvent event) {

		logger.info("ActionCommand=" + event.getActionCommand());
		if ("delete".equals(event.getActionCommand())) {

			int[] selectedRows = table.getSelectedRows();
			new DeleteAction(selectedRows).start();
		
		} else if ("choose".equals(event.getActionCommand())) {
		
			showCoosePssFileDialog();
		
		} else if ("add".equals(event.getActionCommand())) {
		
			File file = chooseImportFile();
			if (file != null) {
				new ImportAction(file).start();
			}
		} else if ("exit".equals(event.getActionCommand())) {
			this.dispose();
		} else if ("help".equals(event.getActionCommand())) {
			;
			new Popup(_instance,ServiceLocator.getText("helpfile"));
		}
	}

	private File chooseImportFile() {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(getDefaultAudioDir());
		int returnVal = chooser.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File selectedFile = chooser.getSelectedFile();
			logger.info("Selected File=" + selectedFile);
			if (selectedFile != null) {
				ServiceLocator.getPreferences().put(KEY_DEFAULT_AUDIO_DIR,
						selectedFile.toString());
			}
			return selectedFile;
		}
		return null;
	}

	private void showCoosePssFileDialog() {
		JFileChooser chooser = new JFileChooser();

		FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File file) {
				if (file == null) {
					return false;
				}
				if (file.isDirectory()) {
					return true;
				}
				return "MyDb".equals(file.getName());
			}

			@Override
			public String getDescription() {
				return ServiceLocator.getText("Frame.file.dialog");
			}
		};
		chooser.setFileFilter(filter);
		chooser.setCurrentDirectory(getDefaultPssDir());
		int returnVal = chooser.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File selectedFile = chooser.getSelectedFile();
			logger.info("Selected File=" + selectedFile);
			ServiceLocator.setSqliteDir(selectedFile);
			// execute it in the same thread 
			// and update when it returns
			new DefaultDataAction().start();
		}

	}

	public static void showMessage(String message, Throwable error) {
		logger.debug(message, error);
		StringBuilder builder = new StringBuilder();
		builder.append("<html><p>");
		builder.append(message);
		builder.append("</p>");
		if (error != null) {
			builder.append("<pre><small>");
			builder.append(error.getMessage());
			for (StackTraceElement se : error.getStackTrace()) {
				builder.append("<br/>");
				builder.append(se.toString());
			}
			builder.append("</small></pre>");
		}
		builder.append("</html>");
		JOptionPane.showMessageDialog(_instance, builder.toString(), "Error",
				JOptionPane.ERROR_MESSAGE);
	}

	public static void startProgress() {
		progressBar.setVisible(true);
	}

	public static void stopProgress() {
		progressBar.setVisible(false);
	}
	
	public static boolean isInProgress() {
		return progressBar.isVisible();
	}

	public static final String KEY_DEFAULT_PSS_DIR = "defaultPssDir";

	public static final String KEY_DEFAULT_AUDIO_DIR = "defaultAudioDir";

	private File getDefaultPssDir() {
		return new File(ServiceLocator.getPreferences().get(
				KEY_DEFAULT_PSS_DIR, System.getProperty("user.home")));
	}

	private File getDefaultAudioDir() {
		return new File(ServiceLocator.getPreferences().get(
				KEY_DEFAULT_AUDIO_DIR, System.getProperty("user.home")));
	}
}
